package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import com.itheima.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/setmeal")
public class SetmealController {

   @Reference
   private SetmealService setmealService;
   @Autowired
   private JedisPool jedisPool;

   //添加套餐
   @RequestMapping("/add/{checkGroupIds}")
   public Result add(@RequestBody Setmeal setmeal, @PathVariable Integer[] checkGroupIds) {
      try {
         //调用添加服务
         setmealService.add(setmeal, checkGroupIds);
      } catch (Exception e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.ADD_SETMEAL_FAIL);//添加套餐失败
      }
      return new Result(true, MessageConstant.ADD_SETMEAL_SUCCESS);//添加套餐成功
   }

   //上传图片
   @RequestMapping("/upload")
   public Result upload(MultipartFile imgFile) {
      try {
         //1.处理文件名字,使用uuid防止文件重名覆盖现象
         String originalFilename = imgFile.getOriginalFilename();//原始名字
         int index = originalFilename.lastIndexOf("."); //获取最后一个点的位置
         String suffix = originalFilename.substring(index); //获取后缀
         String fileName = UUID.randomUUID() + suffix;//拼接文件名

         //2.图片上传
         QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);

         //3.添加上传的名字到redis中
         jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);

         return new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);//上传成功

      } catch (IOException e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);//上传失败
      }

   }

   //分页查询
   @RequestMapping("/findPage")
   public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {

      PageResult pageResult = setmealService.findPage(queryPageBean);

      return pageResult;
   }
}
